package com.budweiser.user.service.impl;

import com.budweiser.commons.utils.PageUtil;
import com.budweiser.model.page.Page;
import com.budweiser.model.user.Permission;
import com.budweiser.model.user.Role;
import com.budweiser.model.user.constants.UserCenterMq;
import com.budweiser.user.dao.RoleDao;
import com.budweiser.user.dao.RolePermissionDao;
import com.budweiser.user.dao.UserRoleDao;
import com.budweiser.user.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private RolePermissionDao rolePermissionDao;
	@Autowired
	private AmqpTemplate amqpTemplate;
	@Autowired
	private UserRoleDao userRoleDao;
	@Override
	public Page<Role> findRoles(Map<String, Object> params) {
		log.info("查询角色列表{}", params);
		int count = roleDao.count(params);
		List<Role> roles = Collections.emptyList();
		if (count > 0) {
			PageUtil.pageParamConver(params, true);
			roles = roleDao.findData(params);
		}
		return new Page<Role>(count, roles);
	}

	@Override
	public void save(Role role) {
		role.setDeleteStatus(false);
		role.setCreateTime(new Date());
		role.setUpdateTime(new Date());
		Role tempRole = roleDao.findByCode(role.getCode());
		if (tempRole != null) {
			throw new IllegalArgumentException("该角色已存在");
		}
		log.info("新增角色{}", role);
		roleDao.inset(role);
	}

	@Override
	public void update(Role role) {
		role.setUpdateTime(new Date());
		Role tempRole = roleDao.findByCodeAndNoId(role.getCode(), role.getId());
		if (tempRole != null) {
			throw new IllegalArgumentException("该角色已存在");
		}
		log.info("修改角色{}", role);
		roleDao.update(role);
	}

	@Override
	public void deleteRole(List<Long> idList) {
		idList.forEach(id ->{
			Role sysRole = roleDao.findById(id);
			roleDao.delete(id);
			rolePermissionDao.delete(id, null);
			userRoleDao.delete(null, id);
			log.info("删除角色：{}", sysRole);
			// 发布role删除的消息
			amqpTemplate.convertAndSend(UserCenterMq.MQ_EXCHANGE_USER, UserCenterMq.ROUTING_KEY_ROLE_DELETE, id);
		});
	}

	@Override
	public List<Permission> getPermissionList(Long roleid) {
		return rolePermissionDao.getPermissionByRoleid(roleid);
	}
    /***
     * 给角色设置权限
     */
	@Override
	public void setPermissionToRole(Long roleid, List<Long> permissionIds) {
		//先删除该角色所有权限
		rolePermissionDao.delete(roleid,null);
		// 添加权限
				if (!CollectionUtils.isEmpty(permissionIds)) {
					permissionIds.forEach(menuId -> {
						rolePermissionDao.save(roleid, menuId);
					});
		 }
	}
}
